package com.qian.ddj.pay.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.qian.api.ddj.model.*;
import com.qian.api.ddj.service.IBusinessService;
import com.qian.api.ddj.service.IChannelService;
import com.qian.api.ddj.service.IOrderService;
import com.qian.api.ddj.service.IUserService;
import com.qian.api.ddj.util.SignUtils;
import com.qian.ddj.pay.model.Query;
import com.qian.ddj.pay.model.RespBody;
import com.yaowk.api.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
@RestController
@RequestMapping("/query")
public class QueryController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IChannelService channelService;
    @Autowired
    private IBusinessService businessService;

    @RequestMapping
    public RespBody query(Query query) {
        RespBody respBody = new RespBody();
        if (ObjectUtils.isEmpty(query.getUserId())) {
            respBody.setRespInfo("userId不能为空");
            return respBody;
        }
        Map<String, String> map = new TreeMap<>();
        map.put("userId", query.getUserId());
        map.put("outOrderNo", query.getOutOrderNo());
        map.put("sign", query.getSign());
        User user = new User();
        user.setUsername(query.getUserId());
        user = userService.findOne(user);
        boolean verify = SignUtils.verifySign(map, user.getSecretKey());
        if (!verify) {
            respBody.setRespInfo("签名错误");
            return respBody;
        }
        Order order = new Order();
        order.setOutOrderNo(query.getOutOrderNo());
        order = orderService.findOne(order);
        if (ObjectUtils.isEmpty(order)) {
            respBody.setRespInfo("订单不存在");
            return respBody;
        }

        Channel channel = channelService.findChannelByBusinessId(order.getBusinessId());

        switch (channel.getCode()) {
            case "syksm":
                order = syksmQuery(order);
                break;

        }

        respBody.setRespCode("1");
        if (order.getStatus().equals(StatusDict.WAIT_PAY) || order.getStatus().equals(StatusDict.NORMAL)) {
            respBody.setRespInfo("待支付");
        } else {
            respBody.setRespInfo("已支付");
        }
        return respBody;
    }

    private Order syksmQuery(Order order) {
        Map<String, String> map = new LinkedHashMap<>();
        Business business = businessService.findById(order.getBusinessId());

        map.put("p0_Cmd", "QueryTrade");
        map.put("p1_Account", business.getAccount());
        map.put("p2_out_trade_no", order.getOrderNo());
        if (order.getPayType().equals(PayTypeDict.ALI_CODE) || order.getPayType().equals(PayTypeDict.ALI_WAP))
            map.put("p4_plat", "5");
        else if (order.getPayType().equals(PayTypeDict.WX_CODE))
            map.put("p4_plat", "6");
        else {
            return order;
        }

        String sign = SignUtils.params(map);
        sign = DigestUtils.md5Hex(sign + "&key=6053B91D59A173C4D3E636ED105AF097");
        map.put("hmac", sign);
        String body = SignUtils.params(map);
        String rec = HttpUtils.post("http://a.xfpay.cn/api/ApiHandler.ashx", body);
        log.info(rec);

        JSONObject result = JSON.parseObject(rec);
        String data = result.getString("data");
        Map<String, String> dataMap = JSON.parseObject(data, Map.class);
        if ("100".equals(result.get("result"))) {
            if ("TRADE_SUCCESS".equals(dataMap.get("trade_status")) || "TRADE_FINISHED".equals(dataMap.get("trade_status")) || "TRADE_PENDING".equals(dataMap.get("trade_status"))) {
                orderService.orderFinish(order);
                order = orderService.findById(order.getId());
            }
        }
        return order;
    }
//    public Order easyPayQuery(Order order){
//        ApiClient apiClient = ApiClientFactory.newClient("https://gw.ak47pay.com/native/", "ZFCK24000JAXS", "2017102821494327000");
//        ApiRequestBuilder builder=ApiRequestBuilder.newInstance("com.opentech.cloud.easypay.trade.query","0.0.1");
//        builder.addParameter("merchantNo", "ZFCK24000JAXS");
//        builder.addParameter("outTradeNo",order.getOrderNo());
//        ApiResponse response = apiClient.invoke(builder.build());
//        Map<String,String> map = response.getData(Map.class);
//        order.setUpOrderNo(map.get("tradeNo"));
//        log.info("支付状态："+map.get("status"));
//        if (!("WAITING_PAY".equals(map.get("status")) || "PAYED_FAILED".equals(map.get("status")))) {
//            orderService.orderFinish(order);
//            order = orderService.findById(order.getId());
//            return order;
//        }
//        return order;
//
//    }
}
